﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using NLSCAN.MacCtrl;
using ScannerKey;
using System.Threading;

namespace Scan
{
    public partial class frmfwwlhucha : Form
    {
        private bool textBox1Focus = false;
        private bool textBox3Focus = false;
        private Scan scan;
        private NLSScanner scanTest;
        private ScanKey scanner2D = null;
        private ScannerMsgOne ScannerReader;

        private CustomMessageHandler cmh;

        private bool formOpenFlag = false;

        private bool isCanScanner = false;

        bool isGetMessage = false;

        ThreadStart threadStart = null;
        Thread thread = null;

        private delegate void UIDelegateMethodAddtextBox1(string str);
        private void AddtextBox1(string text)
        {

            if (textBox1.InvokeRequired)
            {
                UIDelegateMethodAddtextBox1 ui = new UIDelegateMethodAddtextBox1(AddtextBox1);
                textBox1.Invoke(ui, new object[] { text });
            }
            else
            {
                if (PublicVar.IsAutoAddWlCode)
                {
                    text = PublicVar.autoAddWlCode + text;
                }

                if (!string.IsNullOrEmpty(PublicVar.InterceptStr))
                {
                    if (text.IndexOf("JGW") >= 0)
                    {
                        text = text.Substring(text.IndexOf("-") + 1, text.Length - text.IndexOf("-") - 1);
                    }
                }

                textBox1.Text = text;
            }
        }

        private delegate void UIDelegateMethodAddtextBox3(string str);
        private void AddtextBox3(string text)
        {
            if (textBox3.InvokeRequired)
            {
                UIDelegateMethodAddtextBox3 ui = new UIDelegateMethodAddtextBox3(AddtextBox3);
                textBox3.Invoke(ui, new object[] { text });
            }
            else
            {
                textBox3.Text = text;
            }
        }

        private void scanner2D_OnScannerUp(object sender, EventArgs e)
        {
            isCanScanner = false;
            isGetMessage = false;
        }

        private void scanner2D_OnScannerDown(object sender, EventArgs e)
        {
            formOpenFlag = true;
            isCanScanner = true;
        }

        private void DoWork()
        {
            ScannerMsg.ResCode resCode;

            ScannerMsg.DecodeMessage decodeMessage = new ScannerMsg.DecodeMessage();

            decodeMessage.message = new Char[1024];
            decodeMessage.codeID = new Char[256];
            decodeMessage.symLetter = new Char[256];
            decodeMessage.symModifer = new Char[256];
            decodeMessage.length = 1024;

            while (formOpenFlag)
            {
                Thread.Sleep(100);

                while (isCanScanner)
                {
                    Thread.Sleep(20);

                    if (isGetMessage)
                    {
                        break;
                    }

                    resCode = ScannerMsg.oemWaitForDecode(1, decodeMessage.message, decodeMessage.codeID, decodeMessage.symLetter, decodeMessage.symModifer, ref decodeMessage.length, null);

                    if (resCode == ScannerMsg.ResCode.RESULT_ERR_NODECODE)
                    {
                        continue;
                    }
                    else if (resCode == ScannerMsg.ResCode.RESULT_ERR_NOTRIGGER)
                    {
                        break;
                    }
                    else if (resCode == ScannerMsg.ResCode.RESULT_SUCCESS)
                    {
                        String msg = new String(decodeMessage.message);

                        try
                        {
                            AppendMessage(msg.Trim());
                           // Sound.PlaySoundFile(@"\\windows\\beeph.wav");
                            Sound.Beep();
                            isGetMessage = true;
                        }
                        catch (System.Exception e)
                        {

                        }

                        break;
                    }
                }
            }
        }

        delegate void DelegateFun(String message);

        private void AppendMessage(String message)
        {

            if (textBox1Focus)
            {
                AddtextBox1(message);
            }
            
            if (textBox3Focus)
            {
                AddtextBox3(message);
            }
        }

        private void MovFormControl()
        {
            label1.Location = new Point(label1.Location.X, label1.Location.Y + 20);
            textBox1.Location = new Point(textBox1.Location.X, textBox1.Location.Y + 20);

            label3.Location = new Point(label3.Location.X, label3.Location.Y + 20);
            textBox3.Location = new Point(textBox3.Location.X, textBox3.Location.Y + 20);

            label2.Location = new Point(label2.Location.X, label2.Location.Y + 20);
            textBox2.Location = new Point(textBox2.Location.X, textBox2.Location.Y + 20);
            textBox2.Height = textBox2.Height - 20;
        }


        public frmfwwlhucha()
        {
            InitializeComponent();

            if (PublicVar.SeiBei == SeiBeiClass.baoxun)
            {
                scan = new Scan();
                scan.RegisterHotKey();
                scan.Process += new ProcessDelegate(Scan_Process);
            }
            else if (PublicVar.SeiBei == SeiBeiClass.xindalu)
            {
                scanTest = new NLSCAN.MacCtrl.NLSScanner();
                scanTest.OnDecodeEvent += new DecodeEventHandler(scan_OnDecodeEvent);
                scanTest.Open();
                // scanTest.StartScan(true);
                MovFormControl();
                
            }
            else if (PublicVar.SeiBei == SeiBeiClass.AutoIDOne)
            {
                this.ScannerReader = new ScannerMsgOne(this);

                if (ScannerMsgOne.SSI_Register((IntPtr)ScannerReader.Hwnd, (uint)ScannerMsgOne.WM_READMSG)) // 初始条码扫描设备
                {
                    //可读扫描数据的事件
                    ScannerReader.OnScannerReader += new ScannerMsgOne.ScannerReader(this.ScanReader);
                }
                MovFormControl();
            }
            else if (PublicVar.SeiBei == SeiBeiClass.AutoID)
            {
                //ScannerMsg.ResCode resCode;
                //resCode = ScannerMsg.oemConnect();
                //if (resCode != ScannerMsg.ResCode.RESULT_SUCCESS)
                //{
                //    MessageBox.Show("oemConnect failed", "提示");
                //    return;
                //}

                //resCode = ScannerMsg.oemEnableSymbologyAll();
                //if (resCode != ScannerMsg.ResCode.RESULT_SUCCESS)
                //{
                //    MessageBox.Show("oemEnableSymbologyAll failed", "提示");
                //    return;
                //}
                //ScannerMsg.oemSetDecodeMode(ScannerMsg.SetupType.SETUP_TYPE_CURRENT, '1');

                //scanner2D = new ScanKey();
                //scanner2D.OnScannerDown += new ScanKey.ScanneKeyDown(scanner2D_OnScannerDown);
                //scanner2D.OnScannerUp += new ScanKey.ScanneKeyUp(scanner2D_OnScannerUp);

                //formOpenFlag = true;
                //threadStart = new ThreadStart(DoWork);
                //thread = new Thread(threadStart);
                //thread.Start();

                SCAN.Scanner2D.Scanner.Instance().OnScanedEvent += new Action<SCAN.Scanner2D.Scanner.CodeInfo>(scanner_OnScanedEvent);
                SCAN.Scanner2D.Scanner.Enable();

                MovFormControl();
            }
            else
            {
                this.cmh = new CustomMessageHandler(this);
                if (!cmh.InitScan())
                {
                    MessageBox.Show("初始化设备失败！");
                    return;
                }

                cmh.OnBarCodeNotify += new CustomMessageHandler.abc(this.OnBarCodeNotify);

                cmh.EnableBeeper(true);
                cmh.EnableVibrater(true);

                MovFormControl();

            }

        }

        void scanner_OnScanedEvent(SCAN.Scanner2D.Scanner.CodeInfo obj)
        {
            if (this.InvokeRequired)
            {
                Action<SCAN.Scanner2D.Scanner.CodeInfo> delegateFun = new Action<SCAN.Scanner2D.Scanner.CodeInfo>(scanner_OnScanedEvent);
                this.Invoke(delegateFun, obj);
            }
            else
            {
                AppendMessage(obj.barcode);
            }
        }

        public void OnBarCodeNotify(byte[] BarCodeData, int nLength)
        {
            try
            {
                string BarCode = Encoding.Default.GetString(BarCodeData, 0, nLength);

                if (textBox1.Focused)
                {
                    if (PublicVar.IsAutoAddWlCode)
                    {
                        textBox1.Text = PublicVar.autoAddWlCode + BarCode;
                    }
                    else if (!string.IsNullOrEmpty(PublicVar.InterceptStr))
                    {
                        if (BarCode.IndexOf("JGW") >= 0)
                        {
                            textBox1.Text = BarCode.Substring(BarCode.IndexOf("-") + 1, BarCode.Length - BarCode.IndexOf("-") - 1);
                        }
                    }
                    else
                    {
                        textBox1.Text = BarCode;
                    }
                }
                if (textBox3.Focused)
                {
                    textBox3.Text = BarCode;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void scan_OnDecodeEvent(object sender, NLSCAN.MacCtrl.ScannerEventArgs e)
        {
            try
            {
                if (textBox1.Focused)
                {
                    if (PublicVar.IsAutoAddWlCode)
                    {
                        textBox1.Text = PublicVar.autoAddWlCode + e.Data;
                    }
                    else if (!string.IsNullOrEmpty(PublicVar.InterceptStr))
                    {
                        if (e.Data.IndexOf("JGW") >= 0)
                        {
                            textBox1.Text = e.Data.Substring(e.Data.IndexOf("-")+1, e.Data.Length - e.Data.IndexOf("-")-1);
                        }
                    }
                    else
                    {
                        textBox1.Text = e.Data;
                    }
                }
                if (textBox3.Focused)
                {
                    textBox3.Text = e.Data;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Scan_Process(object sender, ProcessEventArgs e)
        {
            try
            {
                if (textBox1.Focused)
                {
                    if (PublicVar.IsAutoAddWlCode)
                    {
                        textBox1.Text = PublicVar.autoAddWlCode + e.Barcode;
                    }
                    else if (!string.IsNullOrEmpty(PublicVar.InterceptStr))
                    {
                        if (e.Barcode.IndexOf("JGW") >= 0)
                        {
                            textBox1.Text = e.Barcode.Substring(e.Barcode.IndexOf("-")+1, e.Barcode.Length - e.Barcode.IndexOf("-")-1);
                        }
                    }
                    else
                    {
                        textBox1.Text = e.Barcode;
                    }
                }
                if (textBox3.Focused)
                {
                    textBox3.Text = e.Barcode;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //收到扫描结果的消息
        public void ScanReader(object sender, EventArgs e)
        {
            ScannerMsgOne.BARCODE BarCode = new ScannerMsgOne.BARCODE();

            if (ScannerMsgOne.SSI_GetData(ref BarCode))
            {
                //扫描成功发声音
                ScannerMsgOne.SSI_ReadOK((uint)ScannerMsgOne.ScannerOK.SoundRemind);

                // 获取条码类型名称
                StringBuilder buffer = new StringBuilder();
                buffer.Length = 64;
                ScannerMsgOne.SSI_GetBarcodeName(buffer, buffer.Length);

                // 清除本次扫描的条码
                ScannerMsgOne.SSI_ResetData();

                if (textBox1.Focused)
                {
                    if (PublicVar.IsAutoAddWlCode)
                    {
                        textBox1.Text = PublicVar.autoAddWlCode + BarCode.code.ToString();
                    }
                    else if (!string.IsNullOrEmpty(PublicVar.InterceptStr))
                    {
                        if (BarCode.code.IndexOf("JGW") >= 0)
                        {
                            textBox1.Text = BarCode.code.Substring(BarCode.code.IndexOf("-")+1, BarCode.code.Length - BarCode.code.IndexOf("-")-1);
                        }
                    }
                    else
                    {
                        textBox1.Text = BarCode.code.ToString();
                    }
 
                }

                if (textBox3.Focused)
                {
                   this.textBox3.Text = BarCode.code.ToString();
                }

                // 如果需要连续扫描，延时一段时间后，可以启动下一次扫描。
                // 如果不需要连续扫描，则这段代码不需要。
                // Thread.Sleep(500);
                // ScannerMsg.SSI_StartScan();
            }
        }


        private void menuItem1_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        private string Get_FwWl(string value_fw,string value_wl)
        {
            try
            {
                fwwlCode.fwwlCode fw = new global::Scan.fwwlCode.fwwlCode();
                fw.Url = PublicVar.FWURL;

                string strReturn = fw.Select_fwfcsb(value_fw, value_wl);
                return strReturn;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }


        private void menuItem2_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text.Trim()) && string.IsNullOrEmpty(textBox3.Text.Trim()))
            {
                MessageBox.Show("防伪码或物流码至少要求输入一个");
                return;
            }

            if (!string.IsNullOrEmpty(textBox3.Text.Trim()))
            {
                if ((textBox3.Text.Trim().Length < 12) || (textBox3.Text.Trim().Length > 22))
                {
                    MessageBox.Show("请输入正确的防伪码");
                    return;
                }
            }

            if (!string.IsNullOrEmpty(textBox1.Text.Trim()))
            {
                if ((textBox1.Text.Trim().Length < 12) || (textBox1.Text.Trim().Length > 22))
                {
                    MessageBox.Show("请输入正确的物流码");
                    return;
                }
            }

            try
            {
                textBox2.Text = Get_FwWl(textBox3.Text, textBox1.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show("互查异常" + ex.Message);
                return;
            }

            textBox1.Text = "";
            textBox3.Text = "";
        }

        private void frmwlQuery_Closing(object sender, CancelEventArgs e)
        {
            if (PublicVar.SeiBei == SeiBeiClass.baoxun)
            {
                scan.DisposeCallBack();
            }
            else if (PublicVar.SeiBei == SeiBeiClass.xindalu)
            {
                scanTest.StartScan(false);
                scanTest.Close();
            }
            else if (PublicVar.SeiBei == SeiBeiClass.AutoIDOne)
            {
                ScannerMsgOne.SSI_StopScan();
                ScannerMsgOne.SSI_Unregister((IntPtr)ScannerReader.Hwnd, (uint)ScannerMsgOne.WM_READMSG);
            }
            else if (PublicVar.SeiBei == SeiBeiClass.AutoID)
            {
                //scanner2D.stopListen();
                //isCanScanner = false;
                //formOpenFlag = false;
                SCAN.Scanner2D.Scanner.Instance().OnScanedEvent -= new Action<SCAN.Scanner2D.Scanner.CodeInfo>(scanner_OnScanedEvent);
                SCAN.Scanner2D.Scanner.Disable();
            }
            else
            {
                cmh.CloseBarCode();
            }
        }

        private void textBox1_GotFocus(object sender, EventArgs e)
        {
            textBox1Focus = true;
            textBox3Focus = false;
        }

        private void textBox1_LostFocus(object sender, EventArgs e)
        {
            textBox1Focus = false;
        }

        private void textBox3_GotFocus(object sender, EventArgs e)
        {
            textBox3Focus = true;
            textBox1Focus = false;
        }

        private void textBox3_LostFocus(object sender, EventArgs e)
        {
            textBox3Focus = false;
        }
    }
}